﻿<template>
  <div class="pivot-report-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>閫忚鎶ヨ〃</h3>
          <div class="header-actions">
            <el-button type="primary" @click="generateReport" :loading="generating">
              <el-icon><Refresh /></el-icon>
              鐢熸垚鎶ヨ〃
            </el-button>
            <el-button type="success" @click="exportReport">
              <el-icon><Download /></el-icon>
              瀵煎嚭鎶ヨ〃
            </el-button>
            <el-button type="info" @click="saveReport">
              <el-icon><Document /></el-icon>
              淇濆瓨鎶ヨ〃
            </el-button>
          </div>
        </div>
      </template>

      <div class="report-config">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="config-card">
              <template #header>
                <span>鏁版嵁婧愰厤缃?/span>
              </template>
              <el-form :model="dataSourceConfig" label-width="80px">
                <el-form-item label="鏁版嵁婧?>
                  <el-select v-model="dataSourceConfig.source" placeholder="閫夋嫨鏁版嵁婧? style="width: 100%">
                    <el-option label="閿€鍞暟鎹? value="sales" />
                    <el-option label="閲囪喘鏁版嵁" value="purchase" />
                    <el-option label="搴撳瓨鏁版嵁" value="inventory" />
                    <el-option label="璐㈠姟鏁版嵁" value="finance" />
                  </el-select>
                </el-form-item>
                <el-form-item label="鏃堕棿鑼冨洿">
                  <el-date-picker
                    v-model="dataSourceConfig.dateRange"
                    type="daterange"
                    range-separator="鑷?
                    start-placeholder="寮€濮嬫棩鏈?
                    end-placeholder="缁撴潫鏃ユ湡"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </el-form-item>
                <el-form-item label="绛涢€夋潯浠?>
                  <el-button type="primary" size="small" @click="showFilterDialog">
                    璁剧疆绛涢€?
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>

          <el-col :span="6">
            <el-card class="config-card">
              <template #header>
                <span>琛屽瓧娈?/span>
              </template>
              <div class="field-config">
                <div class="available-fields">
                  <h5>鍙敤瀛楁</h5>
                  <div class="field-list">
                    <div
                      v-for="field in availableFields"
                      :key="field.key"
                      class="field-item"
                      draggable="true"
                      @dragstart="handleDragStart($event, field)"
                    >
                      <el-icon><Grid /></el-icon>
                      <span>{{ field.name }}</span>
                    </div>
                  </div>
                </div>
                <div class="selected-fields">
                  <h5>琛屽瓧娈?/h5>
                  <div
                    class="drop-zone"
                    @drop="handleRowDrop"
                    @dragover="handleDragOver"
                  >
                    <div
                      v-for="(field, index) in rowFields"
                      :key="field.key"
                      class="field-item selected"
                    >
                      <el-icon><Grid /></el-icon>
                      <span>{{ field.name }}</span>
                      <el-button
                        type="danger"
                        size="small"
                        circle
                        @click="removeRowField(index)"
                      >
                        <el-icon><Close /></el-icon>
                      </el-button>
                    </div>
                    <div v-if="rowFields.length === 0" class="drop-placeholder">
                      鎷栨嫿瀛楁鍒版澶?
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>

          <el-col :span="6">
            <el-card class="config-card">
              <template #header>
                <span>鍒楀瓧娈?/span>
              </template>
              <div class="field-config">
                <div class="selected-fields">
                  <h5>鍒楀瓧娈?/h5>
                  <div
                    class="drop-zone"
                    @drop="handleColumnDrop"
                    @dragover="handleDragOver"
                  >
                    <div
                      v-for="(field, index) in columnFields"
                      :key="field.key"
                      class="field-item selected"
                    >
                      <el-icon><Grid /></el-icon>
                      <span>{{ field.name }}</span>
                      <el-button
                        type="danger"
                        size="small"
                        circle
                        @click="removeColumnField(index)"
                      >
                        <el-icon><Close /></el-icon>
                      </el-button>
                    </div>
                    <div v-if="columnFields.length === 0" class="drop-placeholder">
                      鎷栨嫿瀛楁鍒版澶?
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>

          <el-col :span="6">
            <el-card class="config-card">
              <template #header>
                <span>鍊煎瓧娈?/span>
              </template>
              <div class="field-config">
                <div class="selected-fields">
                  <h5>鍊煎瓧娈?/h5>
                  <div
                    class="drop-zone"
                    @drop="handleValueDrop"
                    @dragover="handleDragOver"
                  >
                    <div
                      v-for="(field, index) in valueFields"
                      :key="field.key"
                      class="field-item selected"
                    >
                      <el-icon><Grid /></el-icon>
                      <span>{{ field.name }}</span>
                      <el-select
                        v-model="field.aggregation"
                        size="small"
                        style="width: 80px; margin-left: 8px;"
                      >
                        <el-option label="姹傚拰" value="sum" />
                        <el-option label="璁℃暟" value="count" />
                        <el-option label="骞冲潎" value="avg" />
                        <el-option label="鏈€澶? value="max" />
                        <el-option label="鏈€灏? value="min" />
                      </el-select>
                      <el-button
                        type="danger"
                        size="small"
                        circle
                        @click="removeValueField(index)"
                      >
                        <el-icon><Close /></el-icon>
                      </el-button>
                    </div>
                    <div v-if="valueFields.length === 0" class="drop-placeholder">
                      鎷栨嫿瀛楁鍒版澶?
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <div class="report-result" v-if="reportData.length > 0">
        <el-card>
          <template #header>
            <div class="result-header">
              <span>鎶ヨ〃缁撴灉</span>
              <div class="result-actions">
                <el-button-group>
                  <el-button
                    :type="viewMode === 'table' ? 'primary' : ''"
                    @click="viewMode = 'table'"
                  >
                    琛ㄦ牸瑙嗗浘
                  </el-button>
                  <el-button
                    :type="viewMode === 'chart' ? 'primary' : ''"
                    @click="viewMode = 'chart'"
                  >
                    鍥捐〃瑙嗗浘
                  </el-button>
                </el-button-group>
                <el-select 
                  v-if="viewMode === 'chart'" 
                  v-model="chartType" 
                  style="margin-left: 10px; width: 120px;"
                  @change="updateChartOption"
                >
                  <el-option label="鏌辩姸鍥? value="bar" />
                  <el-option label="鎶樼嚎鍥? value="line" />
                  <el-option label="楗煎浘" value="pie" />
                  <el-option label="鏁ｇ偣鍥? value="scatter" />
                  <el-option label="闆疯揪鍥? value="radar" />
                  <el-option label="婕忔枟鍥? value="funnel" />
                  <el-option label="浠〃鐩? value="gauge" />
                </el-select>
              </div>
            </div>
          </template>

          <div v-if="viewMode === 'table'" class="table-view">
            <el-table
              :data="reportData"
              border
              stripe
              style="width: 100%"
              :max-height="500"
            >
              <el-table-column
                v-for="column in tableColumns"
                :key="column.prop"
                :prop="column.prop"
                :label="column.label"
                :width="column.width"
                :min-width="column.minWidth"
                align="center"
              >
                <template #default="{ row }">
                  <span v-if="column.type === 'number'">
                    {{ formatNumber(row[column.prop]) }}
                  </span>
                  <span v-else>{{ row[column.prop] }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div v-if="viewMode === 'chart'" class="chart-view">
            <div class="chart-container">
              <v-chart
                :option="chartOption"
                style="height: 400px; width: 100%;"
                autoresize
              />
            </div>
          </div>
        </el-card>
      </div>
    </el-card>

    <el-dialog
      v-model="filterDialogVisible"
      title="璁剧疆绛涢€夋潯浠?
      width="600px"
    >
      <el-form :model="filterConfig" label-width="100px">
        <el-form-item
          v-for="(filter, index) in filterConfig.filters"
          :key="index"
          :label="filter.field"
        >
          <el-row :gutter="10">
            <el-col :span="8">
              <el-select v-model="filter.operator" placeholder="鎿嶄綔绗?>
                <el-option label="绛変簬" value="eq" />
                <el-option label="涓嶇瓑浜? value="ne" />
                <el-option label="澶т簬" value="gt" />
                <el-option label="灏忎簬" value="lt" />
                <el-option label="鍖呭惈" value="like" />
                <el-option label="鍦ㄨ寖鍥村唴" value="in" />
              </el-select>
            </el-col>
            <el-col :span="12">
              <el-input v-model="filter.value" placeholder="绛涢€夊€? />
            </el-col>
            <el-col :span="4">
              <el-button type="danger" @click="removeFilter(index)">
                鍒犻櫎
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addFilter">娣诲姞绛涢€夋潯浠?/el-button>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="filterDialogVisible = false">鍙栨秷</el-button>
        <el-button type="primary" @click="applyFilters">纭畾</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, LineChart, PieChart, ScatterChart, RadarChart, FunnelChart, GaugeChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
  BrushComponent,
  MarkLineComponent,
  MarkPointComponent
} from 'echarts/components'
import VChart from 'vue-echarts'

// 娉ㄥ唽蹇呰鐨勭粍浠?
use([
  CanvasRenderer,
  BarChart,
  LineChart,
  PieChart,
  ScatterChart,
  RadarChart,
  FunnelChart,
  GaugeChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
  BrushComponent,
  MarkLineComponent,
  MarkPointComponent
])

// 鍝嶅簲寮忔暟鎹?
const generating = ref(false)
const viewMode = ref('table')
const chartType = ref('bar')
const filterDialogVisible = ref(false)
const draggedField = ref(null)

// 鏁版嵁婧愰厤缃?
const dataSourceConfig = reactive({
  source: 'sales',
  dateRange: []
})

// 绛涢€夐厤缃?
const filterConfig = reactive({
  filters: []
})

// 鍙敤瀛楁
const availableFields = ref([
  { key: 'date', name: '鏃ユ湡', type: 'date' },
  { key: 'customer', name: '瀹㈡埛', type: 'string' },
  { key: 'product', name: '浜у搧', type: 'string' },
  { key: 'category', name: '绫诲埆', type: 'string' },
  { key: 'salesman', name: '閿€鍞憳', type: 'string' },
  { key: 'region', name: '鍦板尯', type: 'string' },
  { key: 'supplier', name: '渚涘簲鍟?, type: 'string' },
  { key: 'warehouse', name: '浠撳簱', type: 'string' },
  { key: 'department', name: '閮ㄩ棬', type: 'string' },
  { key: 'amount', name: '閲戦', type: 'number' },
  { key: 'quantity', name: '鏁伴噺', type: 'number' },
  { key: 'profit', name: '鍒╂鼎', type: 'number' },
  { key: 'cost', name: '鎴愭湰', type: 'number' },
  { key: 'margin', name: '姣涘埄鐜?, type: 'number' },
  { key: 'orders', name: '璁㈠崟鏁?, type: 'number' }
])

// 閫忚琛ㄥ瓧娈甸厤缃?
const rowFields = ref([])
const columnFields = ref([])
const valueFields = ref([])

// 鎶ヨ〃鏁版嵁
const reportData = ref([])

// 璁＄畻灞炴€?
const tableColumns = computed(() => {
  const columns = []
  
  // 娣诲姞琛屽瓧娈靛垪
  rowFields.value.forEach(field => {
    columns.push({
      prop: field.key,
      label: field.name,
      width: 120
    })
  })
  
  // 娣诲姞鍊煎瓧娈靛垪
  valueFields.value.forEach(field => {
    columns.push({
      prop: field.key,
      label: `${field.name}(${getAggregationText(field.aggregation)})`,
      type: 'number',
      width: 120
    })
  })
  
  return columns
})

const chartOption = computed(() => {
  if (reportData.value.length === 0) return {}
  
  // 鏍规嵁瀛楁閰嶇疆鐢熸垚鍥捐〃
  if (rowFields.value.length > 0 && valueFields.value.length > 0) {
    const categories = reportData.value.map(row => row[rowFields.value[0].key])
    const series = valueFields.value.map(field => ({
      name: field.name,
      data: reportData.value.map(row => row[field.key] || 0)
    }))
    
    const baseOption = {
      title: {
        text: '閫忚鎶ヨ〃鍥捐〃',
        left: 'center'
      },
      tooltip: {
        trigger: chartType.value === 'pie' ? 'item' : 'axis'
      },
      legend: {
        data: valueFields.value.map(f => f.name),
        bottom: 0
      }
    }
    
    // 鏍规嵁鍥捐〃绫诲瀷鐢熸垚涓嶅悓鐨勯厤缃?
    switch (chartType.value) {
      case 'bar':
        return {
          ...baseOption,
          grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: categories
          },
          yAxis: {
            type: 'value'
          },
          series: series.map(s => ({
            ...s,
            type: 'bar',
            itemStyle: {
              color: '#409EFF'
            }
          }))
        }
      
      case 'line':
        return {
          ...baseOption,
          grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: categories
          },
          yAxis: {
            type: 'value'
          },
          series: series.map(s => ({
            ...s,
            type: 'line',
            smooth: true,
            itemStyle: {
              color: '#67C23A'
            }
          }))
        }
      
      case 'pie':
        return {
          ...baseOption,
          series: [{
            name: valueFields.value[0]?.name || '鏁版嵁',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['50%', '50%'],
            data: categories.map((category, index) => ({
              name: category,
              value: series[0]?.data[index] || 0
            })),
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            }
          }]
        }
      
      case 'scatter':
        return {
          ...baseOption,
          grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: categories
          },
          yAxis: {
            type: 'value'
          },
          series: series.map(s => ({
            ...s,
            type: 'scatter',
            itemStyle: {
              color: '#E6A23C'
            }
          }))
        }
      
      case 'radar':
        return {
          ...baseOption,
          radar: {
            indicator: categories.map(category => ({
              name: category,
              max: Math.max(...series[0]?.data || [0])
            }))
          },
          series: [{
            name: valueFields.value[0]?.name || '鏁版嵁',
            type: 'radar',
            data: [{
              value: series[0]?.data || [],
              itemStyle: {
                color: '#F56C6C'
              }
            }]
          }]
        }
      
      case 'funnel':
        return {
          ...baseOption,
          series: [{
            name: valueFields.value[0]?.name || '鏁版嵁',
            type: 'funnel',
            left: '10%',
            top: 60,
            bottom: 60,
            width: '80%',
            min: 0,
            max: Math.max(...series[0]?.data || [0]),
            minSize: '0%',
            maxSize: '100%',
            sort: 'descending',
            gap: 2,
            label: {
              show: true,
              position: 'inside'
            },
            data: categories.map((category, index) => ({
              name: category,
              value: series[0]?.data[index] || 0
            }))
          }]
        }
      
      case 'gauge':
        return {
          ...baseOption,
          series: [{
            name: valueFields.value[0]?.name || '鏁版嵁',
            type: 'gauge',
            center: ['50%', '60%'],
            startAngle: 200,
            endAngle: -20,
            min: 0,
            max: Math.max(...series[0]?.data || [0]),
            splitNumber: 10,
            itemStyle: {
              color: '#FFAB91'
            },
            progress: {
              show: true
            },
            pointer: {
              show: false
            },
            axisLine: {
              lineStyle: {
                width: 40
              }
            },
            axisTick: {
              distance: -30,
              splitNumber: 5,
              lineStyle: {
                width: 2,
                color: '#999'
              }
            },
            splitLine: {
              distance: -30,
              length: 30,
              lineStyle: {
                width: 4,
                color: '#999'
              }
            },
            axisLabel: {
              color: '#464646',
              fontSize: 20,
              distance: -60,
              rotate: 'tangential',
              formatter: function (value) {
                if (value === 8750) {
                  return 'Grade A'
                } else if (value === 7000) {
                  return 'Grade B'
                } else if (value === 5250) {
                  return 'Grade C'
                }
                return ''
              }
            },
            title: {
              offsetCenter: [0, '-10%'],
              fontSize: 20
            },
            detail: {
              valueAnimation: true,
              formatter: '{value}',
              color: 'inherit'
            },
            data: [{
              value: series[0]?.data[0] || 0
            }]
          }]
        }
      
      default:
        return baseOption
    }
  }
  
  return {}
})

// 鏂规硶
const handleDragStart = (event, field) => {
  draggedField.value = field
  event.dataTransfer.effectAllowed = 'move'
}

const handleDragOver = (event) => {
  event.preventDefault()
  event.dataTransfer.dropEffect = 'move'
}

const handleRowDrop = (event) => {
  event.preventDefault()
  if (draggedField.value && !isFieldUsed(draggedField.value)) {
    rowFields.value.push({ ...draggedField.value })
    draggedField.value = null
  }
}

const handleColumnDrop = (event) => {
  event.preventDefault()
  if (draggedField.value && !isFieldUsed(draggedField.value)) {
    columnFields.value.push({ ...draggedField.value })
    draggedField.value = null
  }
}

const handleValueDrop = (event) => {
  event.preventDefault()
  if (draggedField.value && !isFieldUsed(draggedField.value)) {
    valueFields.value.push({ 
      ...draggedField.value, 
      aggregation: 'sum' 
    })
    draggedField.value = null
  }
}

const isFieldUsed = (field) => {
  return [...rowFields.value, ...columnFields.value, ...valueFields.value]
    .some(f => f.key === field.key)
}

const removeRowField = (index) => {
  rowFields.value.splice(index, 1)
}

const removeColumnField = (index) => {
  columnFields.value.splice(index, 1)
}

const removeValueField = (index) => {
  valueFields.value.splice(index, 1)
}

const getAggregationText = (aggregation) => {
  const textMap = {
    sum: '姹傚拰',
    count: '璁℃暟',
    avg: '骞冲潎',
    max: '鏈€澶?,
    min: '鏈€灏?
  }
  return textMap[aggregation] || '姹傚拰'
}

const showFilterDialog = () => {
  filterDialogVisible.value = true
}

const addFilter = () => {
  filterConfig.filters.push({
    field: '',
    operator: 'eq',
    value: ''
  })
}

const removeFilter = (index) => {
  filterConfig.filters.splice(index, 1)
}

const applyFilters = () => {
  filterDialogVisible.value = false
  ElMessage.success('绛涢€夋潯浠跺凡搴旂敤')
}

const generateReport = async () => {
  if (valueFields.value.length === 0) {
    ElMessage.warning('璇疯嚦灏戞坊鍔犱竴涓€煎瓧娈?)
    return
  }
  
  generating.value = true
  
  try {
    // 妯℃嫙鐢熸垚鎶ヨ〃鏁版嵁
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 鐢熸垚妯℃嫙鏁版嵁
    const mockData = generateMockData()
    reportData.value = mockData
    
    ElMessage.success('鎶ヨ〃鐢熸垚鎴愬姛')
  } catch (error) {
    ElMessage.error('鎶ヨ〃鐢熸垚澶辫触')
  } finally {
    generating.value = false
  }
}

const generateMockData = () => {
  const data = []
  
  // 鏍规嵁鏁版嵁婧愮敓鎴愪笉鍚岀殑妯℃嫙鏁版嵁
  const dataSources = {
    sales: {
      rowValues: ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05'],
      columnValues: ['鍖椾含', '涓婃捣', '骞垮窞', '娣卞湷'],
      customers: ['寮犱笁', '鏉庡洓', '鐜嬩簲', '璧靛叚'],
      products: ['iPhone 15', 'MacBook Pro', 'iPad Air', 'Apple Watch'],
      categories: ['鐢靛瓙浜у搧', '鏈嶈闉嬪附', '瀹跺眳鐢ㄥ搧', '椋熷搧楗枡'],
      salesmen: ['閿€鍞憳A', '閿€鍞憳B', '閿€鍞憳C'],
      regions: ['鍗庡寳', '鍗庝笢', '鍗庡崡', '瑗垮崡']
    },
    purchase: {
      rowValues: ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05'],
      columnValues: ['鑻规灉渚涘簲鍟?, '鑰愬厠渚涘簲鍟?, '瀹滃渚涘簲鍟?, '鍗庝负渚涘簲鍟?],
      suppliers: ['鑻规灉渚涘簲鍟?, '鑰愬厠渚涘簲鍟?, '瀹滃渚涘簲鍟?, '鍗庝负渚涘簲鍟?],
      products: ['iPhone 15', 'MacBook Pro', 'Nike杩愬姩闉?, '瀹滃瀹跺叿'],
      categories: ['鐢靛瓙浜у搧', '鏈嶈闉嬪附', '瀹跺眳鐢ㄥ搧', '椋熷搧楗枡'],
      departments: ['閲囪喘閮?, '璐㈠姟閮?, '浠撳偍閮?],
      warehouses: ['涓讳粨搴?, '鍒嗕粨搴揂', '鍒嗕粨搴揃']
    },
    inventory: {
      rowValues: ['涓讳粨搴?, '鍒嗕粨搴揂', '鍒嗕粨搴揃', '鍒嗕粨搴揅'],
      columnValues: ['鐢靛瓙浜у搧', '鏈嶈闉嬪附', '瀹跺眳鐢ㄥ搧', '椋熷搧楗枡'],
      products: ['iPhone 15', 'MacBook Pro', 'Nike杩愬姩闉?, '瀹滃瀹跺叿'],
      categories: ['鐢靛瓙浜у搧', '鏈嶈闉嬪附', '瀹跺眳鐢ㄥ搧', '椋熷搧楗枡'],
      warehouses: ['涓讳粨搴?, '鍒嗕粨搴揂', '鍒嗕粨搴揃', '鍒嗕粨搴揅'],
      suppliers: ['鑻规灉渚涘簲鍟?, '鑰愬厠渚涘簲鍟?, '瀹滃渚涘簲鍟?, '鍗庝负渚涘簲鍟?]
    },
    finance: {
      rowValues: ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05'],
      columnValues: ['鏀跺叆', '鏀嚭', '鍒╂鼎', '鎴愭湰'],
      accounts: ['鐜伴噾', '閾惰瀛樻', '搴旀敹璐︽', '搴斾粯璐︽'],
      categories: ['閿€鍞敹鍏?, '閲囪喘鏀嚭', '杩愯惀璐圭敤', '绠＄悊璐圭敤'],
      departments: ['閿€鍞儴', '閲囪喘閮?, '璐㈠姟閮?, '琛屾斂閮?]
    }
  }
  
  const sourceData = dataSources[dataSourceConfig.source] || dataSources.sales
  
  // 鐢熸垚鍩虹鏁版嵁
  const baseData = []
  sourceData.rowValues.forEach(rowValue => {
    sourceData.columnValues.forEach(columnValue => {
      const item = {}
      
      // 娣诲姞琛屽瓧娈靛€?
      if (rowFields.value.length > 0) {
        item[rowFields.value[0].key] = rowValue
      }
      
      // 娣诲姞鍒楀瓧娈靛€?
      if (columnFields.value.length > 0) {
        item[columnFields.value[0].key] = columnValue
      }
      
      // 娣诲姞鍏朵粬瀛楁鐨勯殢鏈哄€?
      availableFields.value.forEach(field => {
        if (!item[field.key]) {
          switch (field.type) {
            case 'date':
              item[field.key] = `${rowValue}-${Math.floor(Math.random() * 28) + 1}`
              break
            case 'string':
              const stringValues = sourceData[field.key] || ['榛樿鍊?]
              item[field.key] = stringValues[Math.floor(Math.random() * stringValues.length)]
              break
            case 'number':
              item[field.key] = Math.floor(Math.random() * 100000) + 10000
              break
            default:
              item[field.key] = '榛樿鍊?
          }
        }
      })
      
      baseData.push(item)
    })
  })
  
  // 鏍规嵁閫忚琛ㄩ厤缃仛鍚堟暟鎹?
  if (rowFields.value.length > 0 && valueFields.value.length > 0) {
    const groupedData = {}
    
    baseData.forEach(item => {
      const rowKey = rowFields.value.map(field => item[field.key]).join('|')
      
      if (!groupedData[rowKey]) {
        groupedData[rowKey] = {}
        rowFields.value.forEach(field => {
          groupedData[rowKey][field.key] = item[field.key]
        })
        valueFields.value.forEach(field => {
          groupedData[rowKey][field.key] = 0
        })
      }
      
      valueFields.value.forEach(field => {
        groupedData[rowKey][field.key] += item[field.key] || 0
      })
    })
    
    return Object.values(groupedData)
  }
  
  return baseData
}

const formatNumber = (value) => {
  if (typeof value === 'number') {
    return value.toLocaleString()
  }
  return value
}

const exportReport = () => {
  ElMessage.success('鎶ヨ〃瀵煎嚭鎴愬姛')
}

const saveReport = () => {
  ElMessage.success('鎶ヨ〃淇濆瓨鎴愬姛')
}

const updateChartOption = () => {
  // 鍥捐〃绫诲瀷鏀瑰彉鏃讹紝閲嶆柊璁＄畻鍥捐〃閰嶇疆
  // 鐢变簬浣跨敤浜哻omputed锛屼細鑷姩鏇存柊
}

// 鐢熷懡鍛ㄦ湡
onMounted(() => {
  // 鍒濆鍖栨暟鎹?
})
</script>

<style scoped>
.pivot-report-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.report-config {
  margin-bottom: 30px;
}

.config-card {
  height: 400px;
}

.config-card .el-card__body {
  height: calc(100% - 40px);
  overflow-y: auto;
}

.field-config {
  height: 100%;
}

.available-fields,
.selected-fields {
  margin-bottom: 20px;
}

.available-fields h5,
.selected-fields h5 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
}

.field-list {
  max-height: 150px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 8px;
}

.field-item {
  display: flex;
  align-items: center;
  padding: 8px;
  margin-bottom: 4px;
  background: #f5f7fa;
  border-radius: 4px;
  cursor: move;
  transition: all 0.3s;
}

.field-item:hover {
  background: #e4e7ed;
}

.field-item.selected {
  background: #ecf5ff;
  border: 1px solid #b3d8ff;
}

.field-item .el-icon {
  margin-right: 8px;
  color: #409EFF;
}

.field-item span {
  flex: 1;
  font-size: 14px;
}

.drop-zone {
  min-height: 150px;
  border: 2px dashed #dcdfe6;
  border-radius: 4px;
  padding: 8px;
  transition: all 0.3s;
}

.drop-zone:hover {
  border-color: #409EFF;
}

.drop-placeholder {
  text-align: center;
  color: #c0c4cc;
  padding: 40px 0;
  font-size: 14px;
}

.report-result {
  margin-top: 20px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-view {
  overflow-x: auto;
}

.chart-view {
  text-align: center;
}

.chart-container {
  width: 100%;
}
</style>
